#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <netinet/in.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>

#define MAXLINE 1024
void
err_sys(const char *fmt, ...);
static void
err_doit(int errnoflag, int level, const char *fmt, va_list ap);

int main(int argc,char **argv){
	int listenfd,connfd;
	char buff[MAXLINE];
	struct sockaddr_in servaddr,cliaddr;
	socklen_t len;
	time_t ticks;
	
	if((listenfd = socket(AF_INET,SOCK_STREAM,0)) < 0){
		perror("socket error");
		exit(-1);
	}
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(13);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0 ){
		err_sys("bind error");
	}
	if(listen(listenfd,10) < 0) {
		err_sys("listen error");
	}
	printf("after listen \n");
	for(;;){
		len = sizeof(cliaddr);
		connfd = accept(listenfd,(struct sockaddr*)&cliaddr,&len);
		printf("get connection from %s and port %d\n ",
			inet_ntop(AF_INET,&cliaddr.sin_addr,buff,sizeof(buff)),ntohs(cliaddr.sin_port));
		ticks = time(NULL);
		snprintf(buff,sizeof(buff),"%.24s\r\n",ctime(&ticks));
		
		if (write(connfd, buff, sizeof(buff)) != sizeof(buff))
			err_sys("write error");
		close(connfd);
	}		
}

void
err_sys(const char *fmt, ...)
{
	va_list		ap;
	va_start(ap, fmt);
	err_doit(1, 0, fmt, ap);
	va_end(ap);
	exit(1);
}


static void
err_doit(int errnoflag, int level, const char *fmt, va_list ap)
{
	int		errno_save, n;
	char	buf[MAXLINE];

	errno_save = errno;		/* value caller might want printed */

	vsprintf(buf, fmt, ap);					/* this is not safe */

	n = strlen(buf);
	if (errnoflag)
		snprintf(buf+n, sizeof(buf)-n, ": %s", strerror(errno_save));
	strcat(buf, "\n");

	fflush(stdout);		/* in case stdout and stderr are the same */
	fputs(buf, stderr);
	fflush(stderr);	
	return;
}

